// pages/shopCar/shopCar.js
var app = getApp();
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    checkAllFlag: false, 
    carList: [], // 正常列表
    shiList: [], // 失效列表
    shopPrice: '0.00', // 总价
    show: false, // 是否展示弹框
    selectList: [], // 选择购买列表
    deletList: [], // 删除列表
    selectIndex: '', // 点击商品下标
    selectFlag: '', // 弹框选中样式
    alertDetail: '', // 弹框商品信息
  },

  getList() {
    this.setData({
      shopPrice: '0.00',
      checkAllFlag: false
    })
    wx.get(wx.api.carList, res=> {
      console.info('=== carList ====', res)
      if (res.data.length > 0) {
        let carList = res.data.filter(item => item.goodsStatus == 1).map( item=> {
          return {...item, checked: false}
        })
        let shiList = res.data.filter(item => item.goodsStatus == 0)
        this.setData({
          carList,
          shiList
        })
      } else {
        this.setData({
          carList: [],
          shiList: []
        })
      }
    })
  },

  toType(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    console.info(index)
    wx.get(`${wx.api.carProduct}${item.goodsId}`, res => {
      console.info('==== carProduct ====', res)
      this.setData({
        selectIndex: index,
        selectFlag: res.data.findIndex(ite => ite.id == item.productId),
        alertDetail: res.data,
        show: true
      })
    })
  },

  tabClick(e) {
    this.setData({
      selectFlag: e.currentTarget.dataset['index']
    })
  },


  toSure() {
    console.info('==== selectIndex ====', this.data.selectIndex)
    let item = this.data.alertDetail[this.data.selectFlag]
    this.setData({
      [`carList[${this.data.selectIndex}].goodsProductName`]: item.specifications,
      [`carList[${this.data.selectIndex}].price`]: item.price,
      [`carList[${this.data.selectIndex}].goodsUrl`]: item.url,
      [`carList[${this.data.selectIndex}].productId`]: item.id,
      selectFlag: '',
      selectIndex: '',
      alertDetail: '',
      show: false
    })
    this.getShopPrice()
  },

  onClose() {
    this.setData({ show: false });
  },

  toSet () {
    this.setData({
      setFlag: !this.data.setFlag
    })
  },

  // 增加数量
  addCount(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    this.setData({
      [`carList[${index}].number`]: item.number + 1
    })
    if (item.number > 99) {
      this.setData({
        [`carList[${index}].number`]: 99
      })
    }
    this.getShopPrice()
  },

  // 减少数量
  subCount(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    if (item.number <= 1) return
    this.setData({
      [`carList[${index}].number`]: item.number - 1
    })
    this.getShopPrice()
  },

  bindKeyInput(e) {
    let index = e.currentTarget.dataset.index
    let reg = /^([1-9]\d|\d)$/
    console.log(e.detail.value, reg.test(e.detail.value))
    if (reg.test(e.detail.value)) {
      if (e.detail.value < 1) {
        this.setData({
          [`carList[${index}].number`]: 1
        })
      } else if (e.detail.value > 99) {
        this.setData({
          [`carList[${index}].number`]: 99
        })
      } else {
        this.setData({
          [`carList[${index}].number`]: e.detail.value
        })
      }
    } else {
      if(e.detail.value.length > 1) {
        this.setData({
          [`carList[${index}].number`]: 99
        })
      } else {
        this.setData({
          [`carList[${index}].number`]: ''
        })
      }
    }
  },

  bindKeyBlur(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    if (!item.number) {
      this.setData({
        [`carList[${index}].number`]: 1
      })
    }
    if (item.goodsCount < 10) {
      this.setData({
        cursorFlag: 0
      })
    }
    if (item.checked) this.getShopPrice()
  },

  // 清空购物车
  clearCar() {
    let ids = ''
    this.data.shiList.forEach((item, index) => {
      if (index == 0) {
        ids += item.id
      } else {
        ids += ',' + item.id
      }
    })
    wx.get(`${wx.api.carDeletes}${ids}`,res=> {
      console.info('==== delete ====', res)
      if (res.code == 200) {
        this.getList()
      }
    })
  },
  
  // 全选 全不选
  checkALL() {
    let flag = this.data.checkAllFlag
    this.setData( {
      checkAllFlag: !this.data.checkAllFlag,
    })
    this.data.carList.forEach((item, index) => {
      this.setData({
        [`carList[${index}].checked`]: !flag,
      })
    })
    this.getShopPrice()
  },

  submit() {
    let list = this.data.carList.filter(item => item.checked)
    if (list.length <= 0) {
      Dialog.alert({
        title: '温馨提示',
        message: '您还没有选择宝贝哦',
        confirmButtonText: '好的'
      })
      return
    }
    wx.setStorage({
      key:"shopDetail",
      data: list,
      success() {
        wx.navigateTo({
          url: '/pages/shopOrderConfirm/orderConfirm?fromPage=shopCar'
        })
      }
    })
  },

  delete() {
    let list = this.data.carList.filter(item => item.checked)
    if (list.length <= 0) {
      Dialog.alert({
        title: '温馨提示',
        message: '您还没有选择宝贝哦',
        confirmButtonText: '好的'
      })
      return
    }
    Dialog.confirm({
        title: '温馨提示',
        message: `确认将这${list.length}个宝贝删除`,
        confirmButtonText: '删除',
        cancelButtonText: '我再想想'
      }).then(() => {
        let ids = ''
        list.forEach((item, index) => {
          if (index == 0) {
            ids += item.id
          } else {
            ids += ',' + item.id
          }
        })
        wx.get(`${wx.api.carDeletes}${ids}`,res=> {
          console.info('==== delete ====', res)
          if (res.code == 200) {
            this.getList()
          }
        })
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getList()
  },

  changeSignFlag(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    this.setData({
      [`carList[${index}].checked`]: !item.checked
    })
    this.getShopPrice()
    if (this.data.carList.findIndex(item => item.checked == false) == -1) {
      this.setData({
        checkAllFlag: true
      })
    } else {
      this.setData({
        checkAllFlag: false
      })
    }
  },

  // 计算总价
  getShopPrice() {
    let checkList = this.data.carList.filter(item => item.checked)
    if (checkList.length > 0) {
      let shopPrice = 0
      checkList.forEach(item => {
        shopPrice += item.price * item.number * 100
      })
      this.setData({
        shopPrice: shopPrice / 100
      })
    } else {
      this.setData({
        shopPrice: '0.00'
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})